package com.geek.javaCource.demo;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicLong;

/**
 * Create by chenhd on 2021/9/18.
 */
@Component
public class Insert100Service {
    @Autowired
    JdbcTemplate jdbcTemplate;

    //使用自己定义的id，避免高并发下自增锁带来性能影响
    AtomicLong idCreator = new AtomicLong(0);
    CountDownLatch countDownLatch = new CountDownLatch(10);

    public void insert100() {
        try {
            System.out.println("========开始执行");
            long startTime = System.currentTimeMillis();
            ExecutorService executorService = Executors.newFixedThreadPool(10);

            //启动10个线程插入
            for (int i = 0; i < 10; i++) {
                executorService.submit(this::insertOperate);
            }
            //等待全部插入完成统计信息
            countDownLatch.await();
            long endTime = System.currentTimeMillis();
            System.out.println("========执行结束，耗时(ms):" + (endTime - startTime));
        } catch (Exception e) {
            //log
            e.printStackTrace();
        }
    }

    private void insertOperate() {
        try {
            for (int round = 0; round < 10; round++) {
                //构造数据，每个线程10个batch，每个batch values中包含1000行
                List<Object[]> dataList = new ArrayList<>();
                //构造sql，values 1000行
                StringBuilder sql = new StringBuilder("INSERT INTO `order`(`id`,`total_price`) VALUES (?,?)");
                for (int batchInsert = 0; batchInsert < 999; batchInsert++) {
                    sql.append(",(?,?)");
                }
                //构造数据,1000组
                for (int i = 0; i < 10; i++) {
                    List<Object> values = new ArrayList<>();
                    for (int batchInsert = 0; batchInsert < 1000; batchInsert++) {
                        values.add(idCreator.incrementAndGet());
                        values.add(100);
                    }
                    dataList.add(values.toArray());
                }

                jdbcTemplate.batchUpdate(sql.toString(), dataList);
            }
        } catch (Exception e) {
            //log
            e.printStackTrace();
        } finally {
            countDownLatch.countDown();
        }
    }
}
